package com.liveims.webims;


import org.apache.log4j.Logger;

import com.liveims.webims.session.IMSManager;
import com.liveims.webims.util.RestPath;
import com.nextenso.proxylet.ProxyletConfig;
import com.nextenso.proxylet.ProxyletException;
import com.nextenso.proxylet.http.BufferedHttpRequestProxylet;
import com.nextenso.proxylet.http.HttpHeaders;
import com.nextenso.proxylet.http.HttpRequest;
import com.nextenso.proxylet.http.HttpRequestProlog;

public class Main implements BufferedHttpRequestProxylet {
	
	private final static Logger log = Logger.getLogger(Main.class);
	RestPath restPath = null;
	
	public int doRequest(HttpRequest request) throws ProxyletException {
		String path = request.getProlog().getURL().getPath();
        restPath = new RestPath(path);
        request.setAttribute("restpath", restPath);
        log.debug("receiving request to "+path);
        HttpHeaders headers = request.getHeaders();
        //if no session exist, ignore the request
        if(headers.getCookie("sessionid")!=null){
        	log.debug("session ID "+ headers.getCookie("sessionid").getValue());
            String sid = headers.getCookie("sessionid").getValue();
            if (IMSManager.hasSession(sid)){
                request.setAttribute("sessionid", sid);
                return NEXT_PROXYLET;
            }
        }
        
        return BufferedHttpRequestProxylet.NEXT_PROXYLET;
        		
	}

	public int accept(HttpRequestProlog prolog, HttpHeaders headers) {
		return ACCEPT;
	}

	public void destroy() {

	}

	public String getProxyletInfo() {
		
		return "IMS WEB 2.0 Framwork";
	}

	public void init(ProxyletConfig cnf) throws ProxyletException {		
	}

}
